package com.lottery.service.qiuqiu.MsgService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.dao.qiuqiu.accoutDao.CustomerServiceDao;
import com.lottery.dao.qiuqiu.accoutDao.UserDao;
import com.lottery.dao.qiuqiu.messageDao.MessageMapper;
import com.lottery.dto.BarrmsgDto;
import com.lottery.dto.Message;
import com.lottery.dto.MessageTube;
import com.lottery.dto.ResultDto;
import com.lottery.entity.BarrageMessage;
import com.lottery.entity.CustomerServiceInformation;
import com.lottery.entity.RobotInfo;
import com.lottery.entity.User;
import com.lottery.initData.InitData;
import com.lottery.utils.DateUtil;
import com.lottery.utils.MessageTubes;
import com.lottery.utils.TouristData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class MsgNoticeService {
    @Autowired
    private UserDao userDao;

    @Resource
    private CustomerServiceDao cusDao;

    @Resource
    private MessageMapper msgDao;

    private MessageTubes messageTubes = MessageTubes.getInstance();

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 插入下注弹幕
     *
     * @param userId  用户id
     * @param barrage 要插入的弹幕
     * @param agencyMark
     * @param result
     * @return
     */
    public String insertBetNotice(int userId, String barrage, int lotteryType, String agencyMark, ResultDto result) {
        logger.debug("下注弹幕插入={}", userId + "  " + barrage);
        JSONObject jObject = new JSONObject();
        User selectId = null;
        try {
            selectId = userDao.selectId(userId);
        } catch (Exception e) {
            jObject.put("result", "1");
            jObject.put("msg", "插入弹幕失败");
            return jObject.toJSONString();
        }
        String body = userId + "::" + selectId.getUserName() + "::" + selectId.getHeadPic() + "::" + barrage;
        Message message = new Message();
        message.setMessageBody(body);
        message.setType("0");
        message.setTimestamp(new Date().getTime());

        MessageTube messageTube;

        //根据agenyId查出对应的消息通道
        String agencyId = selectId.getAgencyId();
        String judge = lotteryType + "bet";
        messageTube = InitData.MESSAGE_GROUP.get(agencyMark).get(judge);


        int push = messageTube.push(message);
        logger.debug("return index={}, {},{},{}", messageTube.getHashCode(), push, message.getType(), body);
        logger.debug("返回的index是={},插入管道={}", push, queryBetNotice(-1, lotteryType, agencyId));
        jObject.put("result", "0");
        jObject.put("msg", "插入弹幕成功");
        return jObject.toJSONString();
    }

    /**
     * 插入提示弹幕
     *
     * @param barrage 要插入的弹幕
     * @return
     */
    public void insertPromptNotice(String barrage, int lotteryType) {
        logger.debug("下注弹幕插入开奖信息={}", barrage);
        Message message = new Message();
        message.setMessageBody(barrage);
        message.setType("1");
        message.setTimestamp(new Date().getTime());
        logger.debug("要插入管道的信息={}", message);

        MessageTube messageTube;
        if (lotteryType == 1) {
            messageTube = messageTubes.getSscBetMessageTube();
        } else {
            messageTube = messageTubes.getPc28BetMessageTube();
        }

        int push = messageTube.push(message);
        logger.debug("return index={},{},{},{}", messageTube.getHashCode(), push, message.getType(), barrage);
    }

    /**
     * 获得下注弹幕
     *
     * @param index 上次查询最后一条记录的index
     * @return
     */
    public String queryBetNotice(int index, int lotteyType, String agencyId) {
        Map<String, Object> maxmap = new HashMap<String, Object>();
        // List<Message> checkMessage2 = new ArrayList<>();
        try {
            // 获得上次到现在的所有弹幕
            List<Message> checkMessage;
            String judge = lotteyType + "bet";
            checkMessage = InitData.MESSAGE_GROUP.get(agencyId).get(judge).checkMessage(index + 1);

            ArrayList<Map<String, String>> listMap = new ArrayList<>();
            if (checkMessage == null) {
                maxmap.put("array", listMap);
                maxmap.put("message", index + "");
                maxmap.put("result", "0");
                maxmap.put("msg", "成功");
                return JSON.toJSONString(maxmap, true);
            }

            long time = new Date().getTime();
            int reIndex = 0;
            for (Message message : checkMessage) {
                if (time - message.getTimestamp() > 120000) {
                    continue;
                }
                Map<String, String> map = new HashMap<String, String>();
                String messageBody = message.getMessageBody();
                if (message.getType().equals("0")) {
                    String[] split = messageBody.split("::");
                    map.put("userId", split[0]);
                    map.put("userName", split[1]);
                    map.put("headPic", split[2]);
                    map.put("barrage", split[3]);
                } else {
                    map.put("barrage", messageBody);
                }
                listMap.add(map);
                reIndex = message.getIndex();
            }
            maxmap.put("array", listMap);
            maxmap.put("message", reIndex + "");
            maxmap.put("result", "0");
            maxmap.put("msg", "成功");
            return JSON.toJSONString(maxmap, true);
        } catch (Exception e) {
            maxmap.put("result", "1");
            maxmap.put("msg", "失败");
            logger.error("queryBetNotice error:", e);
        }
        return JSON.toJSONString(maxmap, true);
    }

    public void tourBetnotice(int userId, String mStr, int lotteyType) {
        String body = userId + "::" + TouristData.touristInfo.get(userId).getTouristName() + "::" + 0 + "::" + mStr;
        Message message = new Message();
        message.setMessageBody(body);
        message.setType("0");
        message.setTimestamp(new Date().getTime());
        MessageTube messageTube = null;
        if (lotteyType == 1) {
            messageTube = MessageTubes.getInstance().getSscBetMessageTube();
        } else if (lotteyType == 2) {
            messageTube = MessageTubes.getInstance().getPc28BetMessageTube();
        }

        int push = messageTube.push(message);
        logger.debug("return index={}, {},{},{}", messageTube.getHashCode(), push, message.getType(), body);
    }


    /**
     * 插入下注弹幕
     *
     * @param userId  用户id
     * @param barrage 要插入的弹幕
     * @return
     */
    public void insertBetNotice(int userId, String barrage, int lotteryType, ResultDto result) {
        logger.debug("下注弹幕插入={}", userId + "  " + barrage);
        User selectId = null;
        try {
            selectId = userDao.selectId(userId);
        } catch (Exception e) {
            logger.error("LobbyService insertBetNotice error,{}", e);
            result.setResultData(false, "插入弹幕消息失败", 11, null);
        }
        String time = DateUtil.getFormatDate("HH:mm:ss");
        String body = userId + "::" + selectId.getUserName() + "::" + selectId.getHeadPic() + "::" + time + "::" + barrage;
        Message message = new Message();
        message.setMessageBody(body);
        message.setType("0");
        message.setTimestamp(new Date().getTime());

        MessageTube messageTube;
        //根据agenyId查出对应的消息通道
        String agencyId = selectId.getAgencyId();
        String judge = lotteryType + "bet";
        messageTube = InitData
                .MESSAGE_GROUP.get(agencyId).get(judge);


        int push = messageTube.push(message);
        logger.debug("return index={}, {},{},{}", messageTube.getHashCode(), push, message.getType(), body);
        result.setMessage("弹幕消息插入成功");
        result.setSuccess(true);
    }
    /**
     * 插入下注弹幕
     *
     * @param userId  用户id
     * @param barrage 要插入的弹幕
     * @return
     */
    public void RobotinsertBetNotice(RobotInfo ro,String barrage, int lotteryType,String agencyMark) {
        logger.debug("下注弹幕插入={}", ro.getRobotId() + "  " + barrage);
        String time = DateUtil.getFormatDate("HH:mm:ss");
        String body = ro.getRobotId() + "::" + ro.getRobotName() + "::" + ro.getRobotPic() + "::" + time + "::" + barrage;
        Message message = new Message();
        message.setMessageBody(body);
        message.setType("0");
        message.setTimestamp(new Date().getTime());

        MessageTube messageTube;
        //根据agenyId查出对应的消息通道
        String judge = lotteryType + "bet";
        messageTube = InitData
                .MESSAGE_GROUP.get(agencyMark).get(judge);


        int push = messageTube.push(message);
        logger.debug("return index={}, {},{},{}", messageTube.getHashCode(), push, message.getType(), body);
    }

    public void queryMessage(Integer userId, String agencyMrak, Integer index, Integer lotteryType, ResultDto result) throws Exception {
        //获取该渠道商的信息通道
        String judge = lotteryType + "bet";
        List<Message> messages = InitData.MESSAGE_GROUP.get(agencyMrak).get(judge).checkMessage(index + 1);

        if (messages == null) {
            result.setResultData(false, "通道无信息", 2, null);
        } else {
            List<Map<String, String>> list = new ArrayList<>();
            //获取两分钟以内的信息
            long time = new Date().getTime();
            int reIndex = 0;
            for (Message message : messages) {
                if (time - message.getTimestamp() > 120000) {
                    continue;
                }
                Map<String, String> map = new HashMap<String, String>();
                String messageBody = message.getMessageBody();
                if (message.getType().equals("0")) {
                    String[] split = messageBody.split("::");
                    String usercheck = userId + "";
                    if (usercheck.equals(split[0])) {
                        continue;
                    }
                    map.put("userId", split[0]);
                    map.put("userName", split[1]);
                    map.put("headPic", split[2]);
                    map.put("betTime", split[3]);
                    map.put("barrage", split[4]);
                } else {
                    map.put("barrage", messageBody);
                }
                list.add(map);
                reIndex = message.getIndex();
                result.setData(reIndex);
                result.setData2(lotteryType);
                result.setResultData(true, "拉取弹幕信息成功", 0, list);
            }

            if (!result.isSuccess()) {
                result.setData(index);
                result.setData2(lotteryType);
                result.setResultData(false, "当前无人下注", 2, null);
            }
        }


    }

    public void insertAllCanalMsg(String stopbet, int lotteyType) {
        Map<String, Map<String, MessageTube>> map = InitData.MESSAGE_GROUP;
        map.forEach((k, v) -> {
            logger.debug("key:" + k + " value:" + v);
            logger.debug("下注弹幕插入开奖信息={}", stopbet);
            Message message = new Message();
            message.setMessageBody(stopbet);
            message.setType("1");
            message.setTimestamp(new Date().getTime());
            logger.debug("要插入管道的信息={}", message);
            MessageTube messageTube = v.get(lotteyType + "bet");
            int push = messageTube.push(message);
            logger.debug("return index={},{},{},{}", messageTube.getHashCode(), push, message.getType(), stopbet);
        });
    }

    public void insertBarrageforUser(Integer agencyMark, Integer userId, String msg, ResultDto result) throws Exception {
        BarrageMessage msginfo = new BarrageMessage();
        msginfo.setAgencyMark(agencyMark);
        msginfo.setInsertTime(new Date());
        msginfo.setUserId(userId);
        msginfo.setState(0);//0:未处理
        msginfo.setMsgInfo(msg);
        msgDao.insert(msginfo);
        result.setResultData(true, "插入聊天记录成功", 0, null);
    }

    @Transactional(rollbackFor = Exception.class)
    public void getMsgInfoFromCusServer(Integer userId, Integer agencyMark, ResultDto result) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("agencyMark", agencyMark);
        params.put("state", 4);
        //获取未拉取问题列表
        List<BarrageMessage> questionList = msgDao.getMsgInfoFromCusServer(params);
        //获取客服返回的答复
        params.put("state", 3);
        List<BarrageMessage> answerList = msgDao.getMsgInfoFromCusServer(params);
        if (questionList.size() > 0 && answerList.size() > 0) {
            //初始化问题集
            LinkedHashMap<Integer, BarrmsgDto> resultMap = new LinkedHashMap<>();
            questionList.forEach((k) -> {
                BarrmsgDto aa = new BarrmsgDto();
                User user = userDao.selectId(k.getUserId());
                aa.setUserName(user.getUserName());
                aa.setQuestionTime(DateUtil.getFormatDate(k.getInsertTime(), "HH:mm:ss"));
                aa.setQuestion(k.getMsgInfo());
                aa.setState(0);
                resultMap.put(k.getId(), aa);
            });

            //加入返回结果
            answerList.forEach((k) -> {
                BarrmsgDto aa = resultMap.get(k.getQuestionId());
                CustomerServiceInformation cus = cusDao.selectById(k.getOperatorId());
                aa.setCusName(cus.getNickName());
                aa.setAnswerTime(DateUtil.getFormatDate(k.getInsertTime(), "HH:mm:ss"));
                aa.setAnswer(k.getMsgInfo());
            });

            resultMap.forEach((k, v) -> {
                if (v.getAnswer() == null || v.getAnswer() == "") {
                    v.setFlag(false);
                } else {
                    v.setFlag(true);
                }
            });

            //改变回复状态
            answerList.forEach((k) -> {
                k.setState(1);
                msgDao.updateByPrimaryKeySelective(k);
            });
            questionList.forEach((k) -> {
                k.setState(1);
                msgDao.updateByPrimaryKeySelective(k);
            });
            List<BarrmsgDto> list = new ArrayList<>();
            resultMap.forEach((k, v) -> {
                list.add(v);
            });
            result.setResultData(true, "拉取客服信息成功", 0, list);
        } else {
            result.setResultData(false, "客服还没回复", 2, null);
        }


    }
}
